---
import { getCollection } from 'astro:content';
import Main from '@/layouts/Main.astro';
import Layout from '@/layouts/Layout.astro';
import Header from '@/components/Header.astro';
import Footer from '@/components/Footer.astro';
import Card from '@/components/Card.astro';
import getArchives from '@/utils/getArchives';
import config from '@/config';

const posts = await getCollection('blog', ({ data }) => !data.draft);

const months = [
  'January',
  'February',
  'March',
  'April',
  'May',
  'June',
  'July',
  'August',
  'September',
  'October',
  'November',
  'December',
];
---

<Layout title={`Archives | ${config.title}`}>
  <Header />
  <Main pageTitle="Archives">
    {
      Object.entries(getArchives(posts, post => post.data.pubDatetime.getFullYear()))
        .sort(([yearA], [yearB]) => Number(yearB) - Number(yearA))
        .map(([year, yearGroup]) => (
          <div>
            <span class="text-2xl font-bold">{year}</span>
            <sup class="text-sm">{yearGroup.length}</sup>
            {Object.entries(getArchives(yearGroup, post => post.data.pubDatetime.getMonth() + 1))
              .sort(([monthA], [monthB]) => Number(monthB) - Number(monthA))
              .map(([month, monthGroup]) => (
                <div class="flex flex-col sm:flex-row">
                  <div class="mt-6 min-w-36 text-lg sm:my-6">
                    <span class="font-bold">{months[Number(month) - 1]}</span>
                    <sup class="text-xs">{monthGroup.length}</sup>
                  </div>
                  <ul>
                    {monthGroup
                      .sort(
                        (a, b) =>
                          Math.floor(new Date(b.data.pubDatetime).getTime() / 1000) -
                          Math.floor(new Date(a.data.pubDatetime).getTime() / 1000)
                      )
                      .map(data => (
                        <Card {...data} excerpt={false} />
                      ))}
                  </ul>
                </div>
              ))}
          </div>
        ))
    }
  </Main>
  <Footer />
</Layout>
